package com.yiyw.herostory.handler;

import com.yiyw.herostory.bo.UserBo;
import com.yiyw.herostory.manage.ChannelGroupManage;
import com.yiyw.herostory.manage.UserManage;
import com.yiyw.herostory.pojo.UserEntity;
import com.yiyw.herostory.proto.GameMsgProtocol;
import com.yiyw.herostory.service.UserService;
import com.yiyw.herostory.util.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author yiyw
 * @Description 用户登录逻辑
 * @Date 2022/8/21 14:41
 **/
@Slf4j
public class UserLoginCmdHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd> {

    UserService userService = SpringUtil.getBean(UserService.class);

    @Override
    public void handler(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd msg) {
        if (msg == null || StringUtils.isAnyBlank(msg.getUserName(), msg.getPassword())) {
            return;
        }
        UserEntity entity = new UserEntity();
        entity.setUserName(msg.getUserName());
        entity.setPassword(msg.getPassword());
        entity.setHeroAvatar("");
        UserEntity loginUser = userService.login(entity);

        if (loginUser == null) {
            log.error("密码错误");
            return;
        }

        GameMsgProtocol.UserLoginResult.Builder result = GameMsgProtocol.UserLoginResult.newBuilder();
        result.setUserId(loginUser.getUserId());
        result.setUserName(loginUser.getUserName());
        result.setHeroAvatar(loginUser.getHeroAvatar());
        // 保存用户ID到单腔channel
        ChannelGroupManage.bingUserIdToChannel(ctx.channel(), loginUser.getUserId());
        if (!StringUtils.isBlank(loginUser.getHeroAvatar())) {
            UserManage.addUser(new UserBo(loginUser.getUserId(), loginUser.getHeroAvatar()));
        }


        ctx.channel().writeAndFlush(result.build());
    }
}
